import { gp } from '@vui'
import isEmpty from 'lodash/isEmpty'
import trim from 'lodash/trim'
import isPlainObject from 'lodash/isPlainObject'
import { processingConstant } from '@ve/utils/utils'
import qs from 'qs'
import { translateTitle } from '@/utils/i18n'

//必须带done回调 执行完成调用
export default function openLink({ vm, action, callbackData, done }) {
  if (!action.extension.url.value) {
    done(null, {})
    return
  }

  if (vm.$store.getters['preview/getDev']) {
    gp.$baseMessage(translateTitle('Ve.eventTask.预览阶段不执行跳转链接'), 'warning')
    done(null, {})
    return
  }
  let _data = {}
  if (!isEmpty(callbackData)) {

    if (isPlainObject(callbackData.data)) {
      // 如果有 data 值且为对象的话 则认为是接口返回值，则取data下的值
      _data = callbackData.data[Object.keys(callbackData.data)[0]]
    } else {
      _data = callbackData
    }
  }

  let param = {}
  if (action.extension.param) {
    let _arr = action.extension.param.value.split(',')
    _arr.forEach((v) => {
      if (!isEmpty(v)) {
        let _key = trim(v)
        if (_key.match(/#.*?#/g)) {
          // 做常量获取
          const _value = processingConstant(vm, _key)
          // 赋值
          param[_key.slice(1, -1)] = _value
        } else {
          if (Array.isArray(_data)) {
            // 如果是数组则需要进行值拼接
            const valList = []
            _data.forEach((i) => {
              valList.push(i[_key])
            })
            param[_key] = valList.join()
          } else {
            param[_key] = _data[_key]
          }
        }

      }
    })
  }
  let _url = ``
  if (isEmpty(param)) {
    _url = `${action.extension.url.value}`
  } else {
    _url = `${action.extension.url.value}?${qs.stringify(param)}`
  }

  console.log('openLink:', _url.slice(1))
  if (action.extension.hasNewOpenWindow.value) {
    window.open(_url)
  } else {
    // location.href = _url
    vm.$router.push(_url.slice(1))
  }
  setTimeout(() => {
    done(null, {})
  }, 1000)
}
